package com.rockwell.sniffyhunter.model;

import com.rockwell.sniffyhunter.utils.IMazeSolver;

public class LeftFirstMazeSolver implements IMazeSolver {
	private RobotCommand m_com = new RobotCommand();
	boolean m_firstJunctionReached = false;
	IMazeSolver m_nestedSolver;
	boolean m_useNestedSolver = false;
	
	@Override
	public RobotCommand nextAction(RobotPosition rp, boolean beforeDetectWall) {
		m_useNestedSolver = !m_useNestedSolver;
		
		if (m_nestedSolver != null) {
			return m_nestedSolver.nextAction(rp, beforeDetectWall);
		}
			
		switch (rp.junctionLocation)
		{
		case LaneLeft2:
		case LaneLeft1:
		case LaneRight2:
		case LaneRight1:
		case LaneCenter:
			m_com.action = RobotAction.Jog;
			break;
		case RightTurnOnlyButTooLeft2:
		case RightTurnOnlyButTooLeft1:
		case RightTurnOnly:
			m_com.action = RobotAction.TurnRight;
			break;
		case TRightStraightButTooLeft2:
		case TRightStraightButTooLeft1:
		case TRightStraight:
			if (m_firstJunctionReached)
				m_com.action = RobotAction.Jog;
			else
				m_com.action = RobotAction.TurnRight;
			break;
		case LeftTurnOnlyButTooRight2:
		case LeftTurnOnlyButTooRight1:
		case LeftTurnOnly:
			m_com.action = RobotAction.TurnLeft;
			break;
		case TLeftStraightButTooRight2:
		case TLeftRStraightButTooRight1:
		case TLeftStraight:
			if (m_firstJunctionReached)
				m_com.action = RobotAction.TurnLeft;
			else
				m_com.action = RobotAction.Jog;
			break;
		case TLeftRight:
			if (m_firstJunctionReached)
				m_com.action = RobotAction.TurnLeft;
			else
				m_com.action = RobotAction.TurnRight;
			break;
		case FourWay:
			if (m_firstJunctionReached)
				m_com.action = RobotAction.TurnLeft;
			else
				m_com.action = RobotAction.TurnRight;
			break;
		case DeadEnd:
			m_com.action = RobotAction.TurnBack;
			break;
		default:
			assert(false);
			break;
		}
		
		return m_com;
	}

	@Override
	public void onJunctionPassed(RobotAction action) {
		m_firstJunctionReached = true;
	}
	
	public void addSolver(IMazeSolver solver) {
		m_nestedSolver = solver;
	}

	@Override
	public void initialize() {
		m_firstJunctionReached = false;
	}
}
